package com.zhkj.txg.module.home.ui

import android.content.Intent
import android.view.View
import android.widget.ImageView
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import com.google.gson.Gson
import com.zhkj.lib.base.ViewModelFragment
import com.zhkj.lib.config.BASE_URL
import com.zhkj.lib.http.HttpResponseStatus
import com.zhkj.lib.utils.AccountManager
import com.zhkj.lib.utils.SPUtil
import com.zhkj.txg.R
import com.zhkj.txg.base.CustomApplication
import com.zhkj.txg.module.home.adapter.CategoryLeftAdapter
import com.zhkj.txg.module.home.adapter.CategoryRightAdapter
import com.zhkj.txg.module.home.entity.ShopInfo
import com.zhkj.txg.module.home.vm.CategoryViewModel
import com.zhkj.txg.utils.ImageUtils
import kotlinx.android.synthetic.main.fragment_category_2.*
import java.lang.Exception

class CategoryFragment2 : ViewModelFragment<CategoryViewModel>() {

    private val categoryLeftAdapter: CategoryLeftAdapter by lazy {
        CategoryLeftAdapter{
            categoryRightAdapter.setNewData(it.child)
            ImageUtils.loadImage(
                this, imageCategoryRightHeard,
                if (it.image.startsWith("http")) it.image else BASE_URL + it.image
            )
        }
    }
    private val categoryRightAdapter = CategoryRightAdapter()

    override fun setViewModel(): CategoryViewModel {
        return createViewModel(true)
    }

    override val layoutResId: Int
        get() = R.layout.fragment_category_2

    override fun initUI() {
        super.initUI()
        // 设置TitleBar的高度
        titleCategoryAll.setFragmentStatusBar()

        with(rvCateLeft) {
            layoutManager = LinearLayoutManager(context)
            adapter = categoryLeftAdapter
        }
        with(rvCateRight) {
            layoutManager = GridLayoutManager(context, 3)
            adapter = categoryRightAdapter
        }

        categoryRightAdapter.setHeaderView(createHeaderView())
        categoryRightAdapter.setOnItemClickListener { adapter, view, position ->
            ProductListActivity.categoryOpen(
                requireContext(), categoryRightAdapter.data[position].name, categoryRightAdapter.data[position].id,
                CustomApplication.getShopId()
            )
        }

        // 跳转门店列表页面
        tvHomeShopList.setOnClickListener {
            val intent = Intent(activity, ShopListActivity::class.java)
            startActivityForResult(intent, 121)
        }

        // 跳转搜索页面
        tvSearch.setOnClickListener {
            SearchActivity.homeOpen(requireActivity(), 0)
        }

    }

    override fun initData() {
        super.initData()

        val shopInfo1 = SPUtil.getInstance().getString(AccountManager.SHOP_INFO)
        val shopInfo2 = try {
            val gson = Gson()
            gson.fromJson<ShopInfo>(shopInfo1, ShopInfo::class.java)
        } catch (e: Exception) {
            null
        }
        if (shopInfo2 == null) {
            val intent = Intent(activity, ShopListActivity::class.java)
            startActivityForResult(intent, 121)
        } else {
            tvHomeShopList.text = shopInfo2.shop_name
            viewModel.shopCate(shopInfo2.id?.toInt()!!).takeIf {
                !it.hasObservers()
            }?.observe(this, Observer { response ->
                handlerResponseStatus(response.status, response.statusTip)
                if (response.status == HttpResponseStatus.Status.SUCCESS) response.response?.let {
                    if (it.data.size == 0) {
                        categoryRightAdapter.setNewData(null)
                        categoryLeftAdapter.setNewData(null)
                        rvCateLeft.visibility = View.GONE
                        rvCateRight.visibility = View.GONE
                    } else {
                        rvCateLeft.visibility = View.VISIBLE
                        rvCateRight.visibility = View.VISIBLE
                        categoryLeftAdapter.setNewData(it.data)
                    }
                }
            })
        }
    }


    private lateinit var imageCategoryRightHeard: ImageView

    private fun createHeaderView(): View {
        return layoutInflater.inflate(R.layout.item_category_header, null).apply {
            imageCategoryRightHeard = findViewById(R.id.imageCategoryRightHeard)
        }
    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == 121 && resultCode == -1 && data != null) {
            val shopInfo = data.getStringExtra(AccountManager.SHOP_INFO)
                ?: return
            SPUtil.getInstance().putString(AccountManager.SHOP_INFO, shopInfo)
            initData()
        }
    }

    override fun onResume() {
        super.onResume()

        initData()
    }
}